package in.falkeninc.umt_v0_9_8_1;

import java.util.ArrayList;
import com.actionbarsherlock.app.SherlockListFragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

/**
 * This class handles the list of various alarms.
 * This is the "top-level" fragment, showing a list of items that the user can pick. Upon picking an item, it takes care of displaying the data to
 * the user as appropriate based on the current UI layout.
 * Displays a list of items that are managed by an adapter similar to ListActivity. 
 * It provides several methods for managing a list view, such as the onListItemClick() callback to handle click events.
 * 
 * @author Eivind Falkenstein
 *
 */
public class TitlesFragment extends SherlockListFragment {

	private boolean mDualPane = false;
	
	public static TitlesFragment tf;
	
	private int mCurCheckPosition = -1;

	private int alarmid = -1;
	private String alarmname = "Default name";
	private String alarmdesc = "Default desc";
	
	private ArrayList<AlarmInfo> results = null;

	public AlarmInfoAdapter arrayAdapter = null;
	
	public DatabaseHandler db;
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		
		super.onActivityCreated(savedInstanceState);

		// You can use getActivity(), which returns the activity associated with a fragment. The activity is a context (since Activity extends Context) .
		db = new DatabaseHandler(getActivity());

//		addTestAlarms(db);
//      logAllAlarms(db);
        
		// Populate list with our SQLite driven array of alarm entries

		// Check to see if we have a frame in which to embed the details fragment directly in the containing UI.
		// R.id.details relates to the res/layout-land/fragment_layout.xml This is first created when the phone is switched to landscape mode
		View detailsFrame = getActivity().findViewById(R.id.details);

		// Check that a view exists and is visible. A view is visible (0) on the screen; the default value. It can also be invisible and hidden, as if the view had not been added.
		mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

		if (savedInstanceState != null) {
			
			// Restore last state for checked position.
			mCurCheckPosition 	= savedInstanceState.getInt("curChoice", 0);
			
			alarmid 			= savedInstanceState.getInt("alarmid");
			alarmname 			= savedInstanceState.getString("alarmname");
			alarmdesc 			= savedInstanceState.getString("alarmdesc");
		}
		dbShowAll();
				
		if (mDualPane) {
			// In dual-pane mode, the list view highlights the selected item.
			getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			// Make sure our UI is in the correct state.
			startDetailsFragment(mCurCheckPosition);
		} else {
			// We also highlight in uni-pane just for fun
			getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			getListView().setItemChecked(mCurCheckPosition, true);
		}	
		
	}
	
	// or else it doesnt work on 2.3
	@Override
	public void onResume() {
	    super.onResume();
	    dbShowAll();
	}

    public void dbShowAll() {
    	
    	DatabaseHandler db = new DatabaseHandler(getActivity());

        this.results =  db.getAllAlarms();
        
        // Log.d("Got getAllAlarms with size: ", String.valueOf(this.results.size())); // Writing Contacts to log
        
        // context -  The current context. 
        // resource - The resource ID for a layout file containing a layout to use when instantiating views. 
        // textViewResourceId - The id of the TextView within the layout resource to be populated  
        // From the third parameter, you plugged the data set to adapter
        arrayAdapter = new AlarmInfoAdapter(getActivity(), R.layout.listview_item_row, this.results);
        arrayAdapter.setNotifyOnChange(true);

        setListAdapter(arrayAdapter);       
        
        

    }

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);

		// Toast.makeText(getActivity(), "onSaveInstanceState", Toast.LENGTH_LONG).show();

		outState.putInt("curChoice", mCurCheckPosition);
		outState.putInt("alarmid", alarmid);
		outState.putString("alarmname", alarmname);
		outState.putString("alarmdesc", alarmdesc);
	}
    
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {

		setSelectedId(v);
		startDetailsFragment(position);
		
	}
	
	/**
	 * Sets the id from our ListView item that was clicked
	 * Here we get the ID that is the actual ID from the database.
	 * This was passed to the myid textview when populating the alarmadapters' getView. (getview gets called for each element)
	 * 
	 * @param v
	 */
	public void setSelectedId(View v) {

		TextView t = (TextView)v.findViewById(R.id.myid);
        this.alarmid = Integer.parseInt(t.getText().toString());
		
        t = (TextView)v.findViewById(R.id.txtName);
        this.alarmname = t.getText().toString();

        t = (TextView)v.findViewById(R.id.txtDesc);
        this.alarmdesc = t.getText().toString();
	}
	
	/**
	 * Starts DetailsFragment as an FragmentActivity if single pane, but plugs the DetailFragment inside MainActivity if in dual pane mode. 
	 * The basic design is multi-pane (landscape on the phone) allows us
	 * to display both fragments (titles and details) with in the same
	 * activity; that is FragmentLayout -- one activity with two
	 * fragments.
	 * 
	 * Else, it's single-pane (portrait on the phone) and we fire
	 * another activity to render the details fragment - two activities
	 * each with its own fragment.
	 * 
	 * @param index
	 * @param alarmid
	 */
	void startDetailsFragment(int index) {
		
		mCurCheckPosition = index;
		
/*		Log.d("[TitlesFragment.showDetails     ]", " mCurCheckPosition = " + String.valueOf(mCurCheckPosition));
		Log.d("[Was called from onListItemClick]", " alarmid = " + alarmid);
		Log.d("[setSelectedId was also called  ]", " alarmname = " + alarmname);
		Log.d("[right before this              ]", " alarmdesc = " + alarmdesc);*/		

		if (mDualPane) {
				doDualPaneDetails(index);
		} else {
				doSinglePaneDetails(index);
		}
	}
	
	/**
	 * Otherwise we need to launch a new activity to display
	 * the dialog fragment with selected text.
	 * That is: if this is a single-pane (e.g., portrait mode on a
	 * phone) then fire DetailsActivity to display the details
	 * fragment
	 * 
	 * @param index
	 * @param alarmid
	 * 
	 */
	public void doSinglePaneDetails(int index) {

		// Create an intent for starting the DetailsActivity
		Intent intent = new Intent();
	
		// Explicitly set the activity context and class associated with the intent (context, class)
		intent.setClass(getActivity(), DetailsActivity.class);
		// pass the current position and ID since we are going into single pane mode
		intent.putExtra("index", index);
		intent.putExtra("alarmid", alarmid);
		intent.putExtra("alarmname", alarmname);
		intent.putExtra("alarmdesc", alarmdesc);
		
/*		Log.d("[TitlesFragment.doSinglePaneDetails]", " mCurCheckPosition = " + String.valueOf(index));
		Log.d("[Was called from onListItemClick   ]", " alarmid = " + alarmid);
		Log.d("[setSelectedId was also called     ]", " alarmname = " + alarmname);
		Log.d("[right before this.                ]", " alarmdesc = " + alarmdesc);
		Log.d("[Now DetailsActivity starts        ]", "yes");*/
	
		startActivity(intent);
	}
	
	/**
	 * We can display everything in-place with fragments, so update the list to highlight the selected item and show the data.
	 * We keep highlighted the current selection.
	 * @param index
	 * @param alarmid
	 */
	public void doDualPaneDetails(int index) {

		getListView().setItemChecked(index, true);
	
		// Check what fragment is currently shown, replace if needed.
		DetailsFragment details = (DetailsFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.details);
		if (details == null || details.getShownIndex() != index) {

			// Make new fragment to show this selection.
			// Send with alarmid, it was set with setSelectedId on onListItemClick
			details = DetailsFragment.newInstance(index,alarmid);
	
			// Execute a transaction, replacing any existing fragment
			// with this one inside the frame.
			// 2 lines for appcompat
			FragmentManager fragMgr = getActivity().getSupportFragmentManager();
			FragmentTransaction ft = fragMgr.beginTransaction();
			ft.replace(R.id.details, details);
			ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
			ft.commit();
		}

/*		Log.d("[TitlesFragment.doDualPaneDetails   ]", " index = " + String.valueOf(index));
		Log.d("[calling DetailsFragment.newInstance]", " [:]");
		Log.d("[and starting fragment besides      ]", " [:]");
		Log.d("[TitlesFragment, both in            ]", " [:]");
		Log.d("[MainActivity's context             ]", " [:]");*/

	}
	
	public void addTestAlarms(DatabaseHandler db) {

		//two primary cases:
		//1. the time was read from the DB as a millisecond timestamp.
		//2. the time was obtained from an UI control
		
		// Inserting alarms
		Log.d("Insert: ", "Inserting test alarms..");
		
		AFW_Time t = new AFW_Time();
	
		String currentstring = String.valueOf(t.getCurrentTimeString());
		
		long currentmillis = t.getCurrentTimeMillis();
		
		String currentparsed = String.valueOf(t.convertDateStringsToMillis("2013", "12", "25", "13", "37", "01"));
		String currentformat = String.valueOf(t.convertDateIntegersToLocalTime(2013, 12, 25, 13, 37, 58));

		Log.d("Calendar: " , currentstring);
		Log.d("r.gettime: " , String.valueOf(currentmillis));
		Log.d("Time parsed: " , currentparsed);
		Log.d("Time ints: " , currentformat);
		
//		db.addAlarm(new AlarmInfo("Ibux", 		"Morgen", 	currentmillis, medicon));

		Log.d("Inserted dates: " , currentstring);
		Log.d("Inserted dates: " , currentformat);
		
	}

	public void logAllAlarms(DatabaseHandler db) {
/*		
	    // Reading all alarms
	    Log.d("Reading: ", "Reading all contacts..");
	    
	    List<AlarmInfo> alarms = db.getAllAlarms();  
	    
	    for (AlarmInfo cn : alarms) {
	        String log = "Id: " 		+ cn.getID()
	        		+ " ,Name: " 		+ cn.getName() 
	        		+ " ,Description: "	+ cn.getDescription()
	        		+ " ,When: " 		+ cn.getAlarmtime();
			Log.d("Name: ", log); // Writing Contacts to log
	    } */

	}
	
	public int getAlarmid() {
		return alarmid;
	}

	public void setAlarmid(int alarmid) {
		this.alarmid = alarmid;
	}

	public String getAlarmname() {
		return alarmname;
	}

	public void setAlarmname(String alarmname) {
		this.alarmname = alarmname;
	}

	public String getAlarmdesc() {
		return alarmdesc;
	}

	public void setAlarmdesc(String alarmdesc) {
		this.alarmdesc = alarmdesc;
	}

	public void update() {
		dbShowAll();
	}	
}
